package com.summer.framework.common.util;

import com.summer.framework.common.entity.BaseEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.UUID;

/**
 * @auther: 杨杰
 * @date: 2019/1/14 10:38
 * @description:
 */
@Data
@Slf4j
public class SetColunmUtil<T> extends BaseEntity {

    public static <T> void setCreateAndUpdateInfo(T entity) {
        setCreateInfo(entity);
        //setUpdatedInfo(entity);
    }

    public static <T> void setCreateInfo(T entity) {
        setId(entity);

        String userId = BaseContext.getUserId();
        if (StringUtils.isEmpty(userId) && ReflectionUtils.hasField(entity, "createdBy")) {
            Object userIdObj = ReflectionUtils.getFieldValue(entity, "createdBy");
            if (null != userIdObj) {
                userId = userIdObj.toString();
            }
        }

        log.info("setCreateInfo userId:" + userId);
        String[] fields = new String[]{"createdBy", "createdTime"};
        Field field = ReflectionUtils.getAccessibleField(entity, "createdTime");
        Object[] value = null;
        if (field != null && field.getType().equals(Date.class)) {
            value = new Object[]{userId, new Date()};
        }
        setDefaultValues(entity, fields, value);
    }

    public static <T> void setId(T entity) {
        String fieldName = "id";
        if (ReflectionUtils.hasField(entity, fieldName) && StringUtils.isBlank((CharSequence) ReflectionUtils.getFieldValue(entity, fieldName))) {
            ReflectionUtils.invokeSetter(entity, fieldName, UUID.randomUUID());
        }

    }

    private static <T> void setDefaultValues(T entity, String[] fields, Object[] value) {
        for (int i = 0; i < fields.length; ++i) {
            String field = fields[i];
            if (ReflectionUtils.hasField(entity, field)) {
                ReflectionUtils.invokeSetter(entity, field, value[i]);
            }
        }
    }
}
